package com.cn.http.http;

import java.io.*;
import java.net.*;

public class DownloadM3U8AndTs {

    public static void main(String[] args) {
        String m3u8Url = "https://t25.cdn2020.com/video/m3u8/2024/08/14/90da3049/index.m3u8"; // M3U8 文件 URL
        String downloadDir = "/Users/apple/Desktop/videos/video_2/"; // 下载目录

        try {
            // 下载 M3U8 文件
            downloadFile(m3u8Url, downloadDir + "playlist.m3u8");

            // 解析 M3U8 文件
            downloadTsFiles(downloadDir + "playlist.m3u8", downloadDir);

            System.out.println("下载完成！");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("下载失败！");
        }
    }

    private static void downloadFile(String urlStr, String destFile) throws IOException {
        URL url = new URL(urlStr);
        try (InputStream in = url.openStream(); FileOutputStream fos = new FileOutputStream(destFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }

    private static void downloadTsFiles(String m3u8File, String downloadDir) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(m3u8File))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.endsWith(".ts")) {
                    String tsUrl = line.startsWith("http") ? line : "https://t25.cdn2020.com/video/m3u8/2024/08/14/90da3049/" + line;
                    downloadFile(tsUrl, downloadDir + line);
                }
            }
        }
    }
}
